scala.scalajs.js.| Scala Examples

The following examples show how to use scala.scalajs.js.|. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: utils.scala    From scala-js-jquery   with Apache License 2.0 5 votes vote down vote up
package io.udash.wrappers.jquery

import scala.scalajs.js
import scala.scalajs.js.|

sealed trait TopLeftCoords {
  def top: Double
  def left: Double
  def toJSDictionary: js.Dictionary[Int | Double] =
    js.Dictionary[Int | Double]("top" -> top, "left" -> left)
}
case class Position(override val top: Double, override val left: Double) extends TopLeftCoords
case class Offset(override val top: Double, override val left: Double) extends TopLeftCoords

case class AnimationOptions(
  duration: Option[Int] = None,
  easing: Option[EasingFunction] = None,
  queue: Option[Boolean] = None,
  step: (Int, js.Dynamic) => Any = null,
  progress: (JQueryPromise[js.Function1[js.Any, js.Any], js.Any], Int, Int) => Any = null,
  complete: () => Any = null,
  start: JQueryPromise[js.Function1[js.Any, js.Any], js.Any] => Any = null,
  done: (JQueryPromise[js.Function1[js.Any, js.Any], js.Any], Boolean) => Any = null,
  fail: (JQueryPromise[js.Function1[js.Any, js.Any], js.Any], Boolean) => Any = null,
  always: (JQueryPromise[js.Function1[js.Any, js.Any], js.Any], Boolean) => Any = null
) {
  def toJSDictionary: js.Dictionary[Any] = {
    val r = js.Dictionary[Any]()
    if (duration.isDefined) r.update("duration", duration.get)
    if (easing.isDefined) r.update("easing", easing.get)
    if (queue.isDefined) r.update("queue", queue.get)
    if (step != null) r.update("step", step)
    if (progress != null) r.update("progress", progress)
    if (complete != null) r.update("complete", complete)
    if (start != null) r.update("start", start)
    if (done != null) r.update("done", done)
    if (fail != null) r.update("fail", fail)
    if (always != null) r.update("always", always)
    r
  }
}


  val easeInQuad: EasingFunction = "easeInQuad"
  val easeOutQuad: EasingFunction = "easeOutQuad"
  val easeInOutQuad: EasingFunction = "easeInOutQuad"
  val easeInCubic: EasingFunction = "easeInCubic"
  val easeOutCubic: EasingFunction = "easeOutCubic"
  val easeInOutCubic: EasingFunction = "easeInOutCubic"
  val easeInQuart: EasingFunction = "easeInQuart"
  val easeOutQuart: EasingFunction = "easeOutQuart"
  val easeInOutQuart: EasingFunction = "easeInOutQuart"
  val easeInQuint: EasingFunction = "easeInQuint"
  val easeOutQuint: EasingFunction = "easeOutQuint"
  val easeInOutQuint: EasingFunction = "easeInOutQuint"
  val easeInExpo: EasingFunction = "easeInExpo"
  val easeOutExpo: EasingFunction = "easeOutExpo"
  val easeInOutExpo: EasingFunction = "easeInOutExpo"
  val easeInSine: EasingFunction = "easeInSine"
  val easeOutSine: EasingFunction = "easeOutSine"
  val easeInOutSine: EasingFunction = "easeInOutSine"
  val easeInCirc: EasingFunction = "easeInCirc"
  val easeOutCirc: EasingFunction = "easeOutCirc"
  val easeInOutCirc: EasingFunction = "easeInOutCirc"
  val easeInElastic: EasingFunction = "easeInElastic"
  val easeOutElastic: EasingFunction = "easeOutElastic"
  val easeInOutElastic: EasingFunction = "easeInOutElastic"
  val easeInBack: EasingFunction = "easeInBack"
  val easeOutBack: EasingFunction = "easeOutBack"
  val easeInOutBack: EasingFunction = "easeInOutBack"
  val easeInBounce: EasingFunction = "easeInBounce"
  val easeOutBounce: EasingFunction = "easeOutBounce"
  val easeInOutBounce: EasingFunction = "easeInOutBounce"
}

object EventName {
  val blur: EventName = "blur"
  val change: EventName = "change"
  val click: EventName = "click"
  val contextMenu: EventName = "contextmenu"
  val dblClick: EventName = "dblclick"
  val focus: EventName = "focus"
  val focusIn: EventName = "focusin"
  val focusOut: EventName = "focusout"
  val keyDown: EventName = "keydown"
  val keyPress: EventName = "keypress"
  val keyUp: EventName = "keyup"
  val mouseDown: EventName = "mousedown"
  val mouseEnter: EventName = "mouseenter"
  val mouseLeave: EventName = "mouseleave"
  val mouseMove: EventName = "mousemove"
  val mouseOut: EventName = "mouseout"
  val mouseover: EventName = "mouseover"
  val mouseUp: EventName = "mouseup"
  val resize: EventName = "resize"
  val scroll: EventName = "scroll"
  val select: EventName = "select"
  val submit: EventName = "submit"
} 
Example 2
Source File: package.scala    From scalajs-react-bridge   with MIT License 5 votes vote down vote up
package com.payalabs.scalajs.react

import scala.concurrent.{ExecutionContext, Future}
import scala.language.experimental.macros
import scala.reflect.ClassTag
import scala.scalajs.js
import scala.scalajs.js.JSConverters._
import scala.scalajs.js.{Object, |}

import japgolly.scalajs.react.component.Js
import japgolly.scalajs.react.vdom.{TagMod, VdomElement, VdomNode}
import japgolly.scalajs.react.{CallbackTo, Children, CtorType}
import japgolly.scalajs.react.vdom.Implicits._

package object bridge extends GeneratedImplicits {
  def writerFromConversion[A](implicit conv: A => js.Any): JsWriter[A] = JsWriter(x => x)
  implicit def stringWriter: JsWriter[String] = writerFromConversion[String]

  implicit def boolWriter: JsWriter[Boolean] = writerFromConversion[Boolean]

  // Note: Char and Long not supported here, since in Scala.js they map to opaque types, which
  // may not map well to the underlying components expectations.
  implicit def byteWriter: JsWriter[Byte] = writerFromConversion[Byte]
  implicit def shortWriter: JsWriter[Short] = writerFromConversion[Short]
  implicit def intWriter: JsWriter[Int] = writerFromConversion[Int]

  implicit def floatWriter: JsWriter[Float] = writerFromConversion[Float]
  implicit def doubleWriter: JsWriter[Double] = writerFromConversion[Double]

  implicit def unitWriter: JsWriter[Unit] = writerFromConversion[Unit]
  implicit def jsAnyWriter[A <: js.Any]: JsWriter[A] = JsWriter(identity)

  implicit def callbackToWriter[T](implicit writerT: JsWriter[T]): JsWriter[CallbackTo[T]] =
    JsWriter(value => value.map(writerT.toJs).runNow())

  implicit def undefOrWriter[A](implicit writerA: JsWriter[A]): JsWriter[js.UndefOr[A]] =
    JsWriter(_.map(writerA.toJs))

  implicit def optionWriter[A](implicit writerA: JsWriter[A]): JsWriter[Option[A]] =
    JsWriter(_.map(writerA.toJs).orUndefined)

  implicit def unionWriter[A, B](implicit A: ClassTag[A],
                                 writerA: JsWriter[A],
                                 B: ClassTag[B],
                                 writerB: JsWriter[B]): JsWriter[A | B] =
    JsWriter { value =>
      A.unapply(value).map(writerA.toJs)
        .orElse(B.unapply(value).map(writerB.toJs))
        .getOrElse(throw new RuntimeException(s"Value $value of type ($A | $B) matched neither}"))
    }

  implicit def enumerationWriter[T <: Enumeration#Value]: JsWriter[T] =
    JsWriter(_.toString)

  implicit def baseSeqWriter[T: JsWriter]: JsWriter[scala.collection.Seq[T]] = {
    val elementWriter = implicitly[JsWriter[T]]

    JsWriter(_.map(elementWriter.toJs).toJSArray)
  }

  implicit def immutableSeqWriter[T : JsWriter]: JsWriter[scala.collection.immutable.Seq[T]] = {
    val elementWriter = implicitly[JsWriter[T]]

    JsWriter((value: scala.collection.immutable.Seq[T]) => js.Array(value.map(e => elementWriter.toJs(e)): _*))
  }

  implicit def mapWriter[T : JsWriter]: JsWriter[Map[String, T]] = {
    val elementWriter = implicitly[JsWriter[T]]

    JsWriter(
      (value: Map[String, T]) => {
        val converted = value.map { case (k, v) => (k, elementWriter.toJs(v)) }
        js.Dictionary(converted.toSeq: _*)
      }
    )
  }

  implicit def futureWriter[A](implicit writeA: JsWriter[A], executionContext: ExecutionContext): JsWriter[Future[A]] =
    JsWriter(_.map(writeA.toJs).toJSPromise)

  implicit def vdomElementWriter: JsWriter[VdomElement] = JsWriter(_.rawElement)

  type JsComponentType = Js.ComponentSimple[Object, CtorType.Summoner.Aux[Object, Children.Varargs, CtorType.PropsAndChildren]#CT, Js.UnmountedWithRawType[Object, Null, Js.RawMounted[Object, Null]]]

  def extractPropsAndChildren(attrAndChildren: Seq[TagMod]): (js.Object, List[VdomNode]) = {
    val b = new japgolly.scalajs.react.vdom.Builder.ToJs {}
    attrAndChildren.toTagMod.applyTo(b)
    b.addClassNameToProps()
    b.addStyleToProps()

    (b.props, b.childrenAsVdomNodes)
  }


} 
Example 3
Source File: ReactContext.scala    From slinky   with MIT License 5 votes vote down vote up
package slinky.core.facade

import slinky.core.{BuildingComponent, ExternalComponent, ExternalPropsWriterProvider}
import slinky.readwrite.Writer

import scala.scalajs.js
import scala.scalajs.js.|

@js.native
trait ReactContextRaw extends js.Object {
  val Provider: js.Object = js.native
  val Consumer: js.Object = js.native
}

case class ContextProviderProps[T](value: T)
object ContextProviderProps {
  implicit def writer[T]: Writer[ContextProviderProps[T]] =
    v =>
      js.Dynamic.literal(
        value = v.value.asInstanceOf[js.Any]
      )
}

class ContextProvider[T](orig: ReactContext[T]) {
  private object External
      extends ExternalComponent()(ContextProviderProps.writer[T].asInstanceOf[ExternalPropsWriterProvider]) {
    override type Props = ContextProviderProps[T]
    override val component: |[String, js.Object] = orig.asInstanceOf[ReactContextRaw].Provider
  }

  def apply(value: T): BuildingComponent[Nothing, js.Object] = External(ContextProviderProps(value))
}

case class ContextConsumerProps[T](children: T => ReactElement)
object ContextConsumerProps {
  implicit def writer[T]: Writer[ContextConsumerProps[T]] =
    v =>
      js.Dynamic.literal(
        children = Writer
          .function1[T, ReactElement](
            _.asInstanceOf[T],
            Writer.jsAnyWriter[ReactElement]
          )
          .write(v.children)
      )
}

class ContextConsumer[T](orig: ReactContext[T]) {
  private object External
      extends ExternalComponent()(ContextConsumerProps.writer[T].asInstanceOf[ExternalPropsWriterProvider]) {
    override type Props = ContextConsumerProps[T]
    override val component: |[String, js.Object] = orig.asInstanceOf[ReactContextRaw].Consumer
  }

  def apply(children: T => ReactElement): BuildingComponent[Nothing, js.Object] =
    External(ContextConsumerProps(children))
}

@js.native
trait ReactContext[T] extends js.Object
object ReactContext {
  implicit final class RichReactContext[T](private val orig: ReactContext[T]) extends AnyVal {
    def Provider: ContextProvider[T] = new ContextProvider[T](orig)
    def Consumer: ContextConsumer[T] = new ContextConsumer[T](orig)
  }
} 
Example 4
Source File: View.scala    From slinky   with MIT License 5 votes vote down vote up
package slinky.vr

import slinky.core.ExternalComponent
import slinky.core.annotations.react

import scala.scalajs.js
import scala.scalajs.js.annotation.JSImport
import scala.scalajs.js.|

case class EdgeInsets(top: Double, bottom: Double, left: Double, right: Double)
case class Layout(x: Double, y: Double, width: Double, height: Double)
case class LayoutEvent(layout: Layout)

@react object View extends ExternalComponent {
  case class Props(
    billboarding: js.UndefOr[String] = js.undefined,
    cursorVisibilitySlop: js.UndefOr[Double | EdgeInsets] = js.undefined,
    hitSlop: js.UndefOr[Double | EdgeInsets] = js.undefined,
    onEnter: js.UndefOr[() => Unit] = js.undefined,
    onExit: js.UndefOr[() => Unit] = js.undefined,
    onHeadPose: js.UndefOr[NativeSyntheticEvent[js.Object] => Unit] = js.undefined,
    onHeadPoseCaptured: js.UndefOr[() => Unit] = js.undefined,
    onInput: js.UndefOr[() => Unit] = js.undefined,
    onInputCaptured: js.UndefOr[() => Unit] = js.undefined,
    onLayout: js.UndefOr[NativeSyntheticEvent[LayoutEvent] => Unit] = js.undefined,
    onMove: js.UndefOr[() => Unit] = js.undefined,
    pointerEvents: js.UndefOr[String] = js.undefined,
    style: js.UndefOr[js.Object] = js.undefined,
    testID: js.UndefOr[String] = js.undefined
  )

  @js.native
  @JSImport("react-360", "View")
  object Component extends js.Object

  override val component = Component
} 
Example 5
Source File: View.scala    From slinky   with MIT License 5 votes vote down vote up
package slinky.native

import slinky.core.ExternalComponent
import slinky.core.annotations.react
import slinky.core.facade.ReactElement

import scala.scalajs.js
import scala.scalajs.js.annotation.JSImport
import scala.scalajs.js.|

case class NativeTouchEvent(
  changedTouches: Seq[Any],
  identifier: String,
  locationX: Int,
  locationY: Int,
  pageX: Int,
  pageY: Int,
  target: String,
  timestamp: Int,
  touches: Seq[Any]
)

case class LayoutRectangle(x: Int, y: Int, width: Int, height: Int)

case class LayoutChangeEvent(layout: LayoutRectangle)

@react object View extends ExternalComponent {
  case class Props(
    onStartShouldSetResponder: js.UndefOr[NativeSyntheticEvent[NativeTouchEvent] => Unit] = js.undefined,
    accessibilityLabel: js.UndefOr[ReactElement] = js.undefined,
    hitSlop: js.UndefOr[BoundingBox] = js.undefined,
    nativeID: js.UndefOr[String] = js.undefined,
    onLayout: js.UndefOr[NativeSyntheticEvent[LayoutChangeEvent] => Unit] = js.undefined,
    onMagicTap: js.UndefOr[() => Unit] = js.undefined,
    onMoveShouldSetResponder: js.UndefOr[NativeSyntheticEvent[NativeTouchEvent] => Boolean] = js.undefined,
    onMoveShouldSetResponderCapture: js.UndefOr[NativeSyntheticEvent[NativeTouchEvent] => Boolean] = js.undefined,
    onResponderGrant: js.UndefOr[NativeSyntheticEvent[NativeTouchEvent] => Unit] = js.undefined,
    onResponderMove: js.UndefOr[NativeSyntheticEvent[NativeTouchEvent] => Unit] = js.undefined,
    onResponderReject: js.UndefOr[NativeSyntheticEvent[NativeTouchEvent] => Unit] = js.undefined,
    onResponderRelease: js.UndefOr[NativeSyntheticEvent[NativeTouchEvent] => Unit] = js.undefined,
    onResponderTerminate: js.UndefOr[NativeSyntheticEvent[NativeTouchEvent] => Unit] = js.undefined,
    onResponderTerminationRequest: js.UndefOr[NativeSyntheticEvent[NativeTouchEvent] => Boolean] = js.undefined,
    accessible: js.UndefOr[Boolean] = js.undefined,
    onStartShouldSetResponderCapture: js.UndefOr[NativeSyntheticEvent[NativeTouchEvent] => Boolean] = js.undefined,
    pointerEvents: js.UndefOr[String] = js.undefined,
    removeClippedSubviews: js.UndefOr[Boolean] = js.undefined,
    style: js.UndefOr[js.Object] = js.undefined,
    testID: js.UndefOr[String] = js.undefined,
    accessibilityComponentType: js.UndefOr[String] = js.undefined,
    accessibilityLiveRegion: js.UndefOr[String] = js.undefined,
    collapsable: js.UndefOr[Boolean] = js.undefined,
    importantForAccessibility: js.UndefOr[String] = js.undefined,
    needsOffscreenAlphaCompositing: js.UndefOr[Boolean] = js.undefined,
    renderToHardwareTextureAndroid: js.UndefOr[Boolean] = js.undefined,
    accessibilityTraits: js.UndefOr[String | Seq[String]] = js.undefined,
    accessibilityViewIsModal: js.UndefOr[Boolean] = js.undefined,
    shouldRasterizeIOS: js.UndefOr[Boolean] = js.undefined
  )

  @js.native
  @JSImport("react-native", "View")
  object Component extends js.Object

  override val component = Component
} 
Example 6
Source File: Slider.scala    From slinky   with MIT License 5 votes vote down vote up
package slinky.native

import slinky.core.ExternalComponent
import slinky.core.annotations.react

import scala.scalajs.js
import scala.scalajs.js.annotation.JSImport
import scala.scalajs.js.|

@react object Slider extends ExternalComponent {
  case class Props(
    style: js.UndefOr[js.Object] = js.undefined,
    disabled: js.UndefOr[Boolean] = js.undefined,
    maximumValue: js.UndefOr[Double] = js.undefined,
    minimumTrackTintColor: js.UndefOr[String] = js.undefined,
    minimumValue: js.UndefOr[Double] = js.undefined,
    onSlidingComplete: js.UndefOr[Double => Unit] = js.undefined,
    onValueChange: js.UndefOr[Double => Unit] = js.undefined,
    step: js.UndefOr[Double] = js.undefined,
    maximumTrackTintColor: js.UndefOr[String] = js.undefined,
    testID: js.UndefOr[String] = js.undefined,
    value: js.UndefOr[Double] = js.undefined,
    thumbTintColor: js.UndefOr[String] = js.undefined,
    maximumTrackImage: js.UndefOr[ImageURISource | Int | Seq[ImageURISource]] = js.undefined,
    minimumTrackImage: js.UndefOr[ImageURISource | Int | Seq[ImageURISource]] = js.undefined,
    thumbImage: js.UndefOr[ImageURISource | Int | Seq[ImageURISource]] = js.undefined,
    trackImage: js.UndefOr[ImageURISource | Int | Seq[ImageURISource]] = js.undefined
  )

  @js.native
  @JSImport("react-native", "Slider")
  object Component extends js.Object

  override val component = Component
} 
Example 7
Source File: ActivityIndicator.scala    From slinky   with MIT License 5 votes vote down vote up
package slinky.native

import slinky.core.ExternalComponent
import slinky.core.annotations.react

import scala.scalajs.js
import scala.scalajs.js.annotation.JSImport
import scala.scalajs.js.|

@react object ActivityIndicator extends ExternalComponent {
  case class Props(
    animating: js.UndefOr[Boolean] = js.undefined,
    color: js.UndefOr[String] = js.undefined,
    size: js.UndefOr[String | Int] = js.undefined,
    hidesWhenStopped: js.UndefOr[Boolean] = js.undefined
  )

  @js.native
  @JSImport("react-native", "ActivityIndicator")
  object Component extends js.Object

  override val component = Component
} 
Example 8
Source File: Picker.scala    From slinky   with MIT License 5 votes vote down vote up
package slinky.native

import slinky.core.ExternalComponent
import slinky.core.annotations.react

import scala.scalajs.js
import scala.scalajs.js.annotation.JSImport
import scala.scalajs.js.|

@react object Picker extends ExternalComponent {
  case class Props(
    onValueChange: js.UndefOr[(String | Int, Int) => Unit] = js.undefined,
    selectedValue: js.UndefOr[String | Int] = js.undefined,
    style: js.UndefOr[js.Object] = js.undefined,
    testID: js.UndefOr[String] = js.undefined,
    enabled: js.UndefOr[Boolean] = js.undefined,
    mode: js.UndefOr[String] = js.undefined,
    prompt: js.UndefOr[String] = js.undefined,
    itemStyle: js.UndefOr[js.Object] = js.undefined
  )

  @js.native
  @JSImport("react-native", "Picker")
  object Component extends js.Object {
    val Item: js.Object = js.native
  }

  override val component = Component

  @react object Item extends ExternalComponent {
    case class Props(label: String, value: String | Int)

    override val component = Component.Item
  }
} 
Example 9
Source File: Image.scala    From slinky   with MIT License 5 votes vote down vote up
package slinky.native

import slinky.core.ExternalComponent
import slinky.core.annotations.react
import slinky.core.facade.ReactElement

import scala.concurrent.Future
import scala.scalajs.js
import scala.scalajs.js.annotation.JSImport
import scala.scalajs.js.|
import scala.scalajs.js.JSConverters._

case class ImageURISource(
  uri: js.UndefOr[String] = js.undefined,
  bundle: js.UndefOr[String] = js.undefined,
  method: js.UndefOr[String] = js.undefined,
  headers: js.UndefOr[js.Object] = js.undefined,
  body: js.UndefOr[String] = js.undefined,
  cache: js.UndefOr[String] = js.undefined,
  width: js.UndefOr[Int] = js.undefined,
  height: js.UndefOr[Int] = js.undefined,
  scale: js.UndefOr[Double] = js.undefined
)

@js.native
trait ImageInterface extends js.Object

case class ImageErrorEvent(error: js.Error)

case class ImageProgressEvent(loaded: Int, total: Int)

@react object Image extends ExternalComponent {
  case class Props(
    style: js.UndefOr[js.Object] = js.undefined,
    blurRadius: js.UndefOr[Int] = js.undefined,
    onLayout: js.UndefOr[NativeSyntheticEvent[LayoutChangeEvent] => Unit] = js.undefined,
    onLoad: js.UndefOr[() => Unit] = js.undefined,
    onLoadEnd: js.UndefOr[() => Unit] = js.undefined,
    onLoadStart: js.UndefOr[() => Unit] = js.undefined,
    resizeMode: js.UndefOr[String] = js.undefined,
    source: js.UndefOr[ImageURISource | Int | Seq[ImageURISource]] = js.undefined,
    loadingIndicatorSource: js.UndefOr[Seq[ImageURISource | Int]] = js.undefined,
    onError: js.UndefOr[NativeSyntheticEvent[ImageErrorEvent] => Unit] = js.undefined,
    testID: js.UndefOr[String] = js.undefined,
    resizeMethod: js.UndefOr[String] = js.undefined,
    accessibilityLabel: js.UndefOr[ReactElement] = js.undefined,
    accessible: js.UndefOr[Boolean] = js.undefined,
    capInsets: js.UndefOr[BoundingBox] = js.undefined,
    defaultSource: js.UndefOr[js.Object | Int] = js.undefined,
    onPartialLoad: js.UndefOr[() => Unit] = js.undefined,
    onProgress: js.UndefOr[NativeSyntheticEvent[ImageProgressEvent] => Unit] = js.undefined
  )

  @js.native
  @JSImport("react-native", "Image")
  object Component extends js.Object {
    def getSize(
      uri: String,
      success: js.Function2[Int, Int, Unit],
      failure: js.UndefOr[js.Function1[js.Error, Unit]]
    ): Unit                                                                   = js.native
    def prefetch(uri: String): Int | Unit                                     = js.native
    def abortPrefetch(requestId: Int): Unit                                   = js.native
    def queryCache(urls: js.Array[String]): js.Promise[js.Dictionary[String]] = js.native
  }

  override val component = Component

  def getSize(uri: String, success: (Int, Int) => Unit, failure: js.UndefOr[(js.Error) => Unit] = js.undefined): Unit =
    Component.getSize(uri, success, failure.map(v => v))

  def prefetch(uri: String): Int | Unit = Component.prefetch(uri)

  def abortPrefetch(requestId: Int): Unit = Component.abortPrefetch(requestId)

  def queryCache(urls: Seq[String]): Future[Map[String, String]] = {
    import scala.scalajs.concurrent.JSExecutionContext.Implicits.queue
    Component.queryCache(urls.toJSArray).toFuture.map(_.toMap)
  }
} 
Example 10
Source File: JSModals.scala    From scalajs-bootstrap   with MIT License 5 votes vote down vote up
package com.karasiq.bootstrap.modal

import scala.language.postfixOps
import scala.scalajs.js
import scala.scalajs.js.|

import com.karasiq.bootstrap.components.BootstrapComponents
import com.karasiq.bootstrap.context.JSRenderingContext
import com.karasiq.bootstrap.jquery.BootstrapJQueryContext

trait JSModals { self: JSRenderingContext with Modals with BootstrapComponents with BootstrapJQueryContext ⇒
  implicit class JSModalOps(modal: Modal) {
    def show(backdrop: Boolean | String = true, keyboard: Boolean = true,
             show: Boolean = true, events: Map[String, js.Any] = Map.empty): Unit = {

      val dialog = jQuery(modal.renderTag().render)
      val options = js.Object().asInstanceOf[JSModalOptions]
      options.backdrop = backdrop
      options.keyboard = keyboard
      options.show = show
      dialog.modal(options)

      dialog.on("hidden.bs.modal", () ⇒ {
        // Remove from DOM
        dialog.remove()
      })

      events.foreach { case (event, handler) ⇒
        dialog.on(event, handler)
      }

      dialog.modal("show")
    }
  }
} 
Example 11
Source File: JSModals.scala    From scalajs-bootstrap   with MIT License 5 votes vote down vote up
package com.karasiq.bootstrap4.modal

import scala.language.postfixOps
import scala.scalajs.js
import scala.scalajs.js.|

import com.karasiq.bootstrap.components.BootstrapComponents
import com.karasiq.bootstrap.context.JSRenderingContext
import com.karasiq.bootstrap.jquery.BootstrapJQueryContext

trait JSModals { self: JSRenderingContext with Modals with BootstrapComponents with BootstrapJQueryContext ⇒
  implicit class JSModalOps(modal: Modal) {
    def show(backdrop: Boolean | String = true, keyboard: Boolean = true,
             show: Boolean = true, events: Map[String, js.Any] = Map.empty): Unit = {

      val dialog = jQuery(modal.renderTag().render)
      val options = js.Object().asInstanceOf[JSModalOptions]
      options.backdrop = backdrop
      options.keyboard = keyboard
      options.show = show
      dialog.modal(options)

      dialog.on("hidden.bs.modal", () ⇒ {
        // Remove from DOM
        dialog.remove()
      })

      events.foreach { case (event, handler) ⇒
        dialog.on(event, handler)
      }

      dialog.modal("show")
    }
  }
} 
Example 12
Source File: Utils.scala    From scalafiddle-editor   with Apache License 2.0 5 votes vote down vote up
package scalafiddle.client

import org.scalajs.dom

import scala.language.implicitConversions
import scala.scalajs.js
import scala.scalajs.js.JSConverters._
import scala.scalajs.js.annotation.JSGlobal
import scala.scalajs.js.typedarray.Uint8Array
import scala.scalajs.js.|

class JsVal(val value: js.Dynamic) {
  def get(name: String): Option[JsVal] = {
    (value.selectDynamic(name): Any) match {
      case () => None
      case v  => Some(JsVal(v.asInstanceOf[js.Dynamic]))
    }
  }

  def apply(name: String): JsVal = get(name).get
  def apply(index: Int): JsVal   = value.asInstanceOf[js.Array[JsVal]](index)

  def keys: Seq[String]  = js.Object.keys(value.asInstanceOf[js.Object]).toSeq.map(x => x: String)
  def values: Seq[JsVal] = keys.map(x => JsVal(value.selectDynamic(x)))

  def isDefined: Boolean = !js.isUndefined(value)
  def isNull: Boolean    = value eq null

  def asDouble: Double   = value.asInstanceOf[Double]
  def asBoolean: Boolean = value.asInstanceOf[Boolean]
  def asString: String   = value.asInstanceOf[String]

  override def toString: String = js.JSON.stringify(value)
}

object JsVal {
  implicit def jsVal2jsAny(v: JsVal): js.Any = v.value

  implicit def jsVal2String(v: JsVal): js.Any = v.toString

  def parse(value: String) = new JsVal(js.JSON.parse(value))

  def apply(value: js.Any) = new JsVal(value.asInstanceOf[js.Dynamic])

  def obj(keyValues: (String, js.Any)*) = {
    val obj = new js.Object().asInstanceOf[js.Dynamic]
    for ((k, v) <- keyValues) {
      obj.updateDynamic(k)(v.asInstanceOf[js.Any])
    }
    new JsVal(obj)
  }

  def arr(values: js.Any*) = {
    new JsVal(values.toJSArray.asInstanceOf[js.Dynamic])
  }
}

@JSGlobal("Zlib.Gzip")
@js.native
class Gzip(data: js.Array[Byte]) extends js.Object {
  def compress(): Uint8Array = js.native
}

@JSGlobal("Zlib.Gunzip")
@js.native
class Gunzip(data: js.Array[Byte]) extends js.Object {
  def decompress(): Uint8Array = js.native
}

@JSGlobal("sha1")
@js.native
object SHA1 extends js.Object {
  def apply(s: String): String = js.native
}

@js.native
@JSGlobal("ScalaFiddleConfig")
object ScalaFiddleConfig extends js.Object {
  val compilerURL: String               = js.native
  val helpURL: String                   = js.native
  val scalaVersions: js.Array[String]   = js.native
  val scalaJSVersions: js.Array[String] = js.native
}

@js.native
@JSGlobal
object Mousetrap extends js.Object {
  def bind(key: String | js.Array[String], f: js.Function1[dom.KeyboardEvent, Boolean], event: String = js.native): Unit =
    js.native

  def bindGlobal(
      key: String | js.Array[String],
      f: js.Function1[dom.KeyboardEvent, Boolean],
      event: String = js.native
  ): Unit = js.native

  def unbind(key: String): Unit = js.native

  def reset(): Unit = js.native
} 
Example 13
Source File: ApolloLink.scala    From apollo-scalajs   with MIT License 5 votes vote down vote up
package com.apollographql.scalajs.link

import com.apollographql.scalajs.DocumentNode
import slinky.readwrite.ObjectOrWritten

import scala.scalajs.js
import scala.scalajs.js.annotation.JSImport
import scala.scalajs.js.|

case class GraphQLRequest(query: DocumentNode)

@js.native
trait FetchResult extends js.Object

@js.native
trait Operation extends js.Object {
  def setContext(context: js.Dictionary[js.Any]): js.Dictionary[js.Any] = js.native
  def getContext(): js.Dictionary[js.Any] = js.native
  def toKey(): String = js.native
}

@JSImport("apollo-link", "ApolloLink")
@js.native
class ApolloLink(handler: js.UndefOr[js.Function2[Operation, js.UndefOr[NextLink], Observable[FetchResult]]] = js.undefined) extends js.Object {
  def concat(next: ApolloLink | RequestHandler): ApolloLink = js.native
  def request(operation: Operation, forward: js.UndefOr[NextLink]): Observable[FetchResult] = js.native
}

@JSImport("apollo-link", "ApolloLink")
@js.native
object ApolloLink extends js.Object {
  def empty(): ApolloLink = js.native
  def from(links: js.Array[ApolloLink]): ApolloLink = js.native
  def concat(first: ApolloLink, second: ApolloLink): ApolloLink = js.native
  def execute(link: ApolloLink, operation: ObjectOrWritten[GraphQLRequest]): Observable[FetchResult] = js.native
} 
Example 14
Source File: TestCombinationChartConfig.scala    From scalajs-highcharts   with MIT License 5 votes vote down vote up
package com.highcharts.test.frontend.charts

import com.highcharts.HighchartsAliases._
import com.highcharts.HighchartsUtils._
import com.highcharts.config.{HighchartsConfig, _}

import scala.scalajs.js
import scala.scalajs.js.annotation.ScalaJSDefined
import scala.scalajs.js.|


@ScalaJSDefined
class TestCombinationChartConfig extends HighchartsConfig {
  override val chart = Chart()

  override val title = Title(text = "Combination chart")

  override val xAxis = XAxis(categories = js.Array("Apples", "Oranges", "Pears", "Bananas", "Plums"))

  override val labels = Labels(items = js.Array(LabelsItems(html = "Total fruit consumption", style = js.Dynamic.literal(
    left = "50px",
    top = "18px",
    color = fromHighchartsTheme("black")(_.textColor)
  ))))

  override val series: SeriesCfg = js.Array[AnySeries](
    SeriesColumn(name = "Jane", data = js.Array[Double](3, 2, 1, 3, 4)),
    SeriesColumn(name = "John", data = js.Array[Double](2, 3, 5, 7, 6)),
    SeriesColumn(name = "Joe", data = js.Array[Double](4, 3, 3, 9, 0)),
    SeriesSpline(name = "Average", data = js.Array[Double](3, 2.67, 3, 6.33, 3.33),
      marker = SeriesSplineMarker(lineWidth = 2, lineColor = defaultColor(3), fillColor = "white")),
    SeriesPie(
      name = "Average",
      data = js.Array(
        SeriesPieData(name = "Jane", y = 13, color = defaultColor(0)),
        SeriesPieData(name = "John", y = 23, color = defaultColor(1)),
        SeriesPieData(name = "Joe", y = 19, color = defaultColor(2))
      ),
      center = js.Array[Double](100, 80),
      size = 100,
      showInLegend = false,
      dataLabels = SeriesPieDataLabels(enabled = false)
    )
  )
} 
Example 15
Source File: JsMessageBuilder.scala    From iotchain   with MIT License 5 votes vote down vote up
package jbok.network.http

import java.nio.ByteBuffer

import cats.effect.{Async, IO}
import org.scalajs.dom.{Blob, Event, FileReader, UIEvent}

import scala.concurrent.Promise
import scala.scalajs.js.typedarray.TypedArrayBufferOps._
import scala.scalajs.js.typedarray._
import scala.scalajs.js.|

trait JsMessageBuilder[F[_], P] {
  import JsMessageBuilder._

  def responseType: String

  def pack(payload: P): Message

  def unpack(msg: Message): F[Option[P]]
}

object JsMessageBuilder {
  type Message = String | ArrayBuffer | Blob

  implicit def JsMessageBuilderString[F[_]](implicit F: Async[F]): JsMessageBuilder[F, String] = new JsMessageBuilder[F, String] {
    val responseType = ""

    def pack(payload: String): Message = payload

    def unpack(msg: Message): F[Option[String]] = (msg: Any) match {
      case s: String => F.pure(Some(s))
      case b: Blob   => readBlob[F, String, String](_.readAsText(b))(identity)
      case _         => F.pure(None)
    }
  }

  implicit def JsMessageBuilderByteBuffer[F[_]](implicit F: Async[F]): JsMessageBuilder[F, ByteBuffer] = new JsMessageBuilder[F, ByteBuffer] {
    val responseType = "arraybuffer"

    def pack(payload: ByteBuffer): Message = payload.arrayBuffer.slice(payload.position, payload.limit)

    def unpack(msg: Message): F[Option[ByteBuffer]] = (msg: Any) match {
      case a: ArrayBuffer => F.pure(Option(TypedArrayBuffer.wrap(a)))
      case b: Blob        => readBlob[F, ArrayBuffer, ByteBuffer](_.readAsArrayBuffer(b))(TypedArrayBuffer.wrap(_))
      case _              => F.pure(None)
    }
  }

  private def readBlob[F[_], R, W](doRead: FileReader => Unit)(conv: R => W)(implicit F: Async[F]): F[Option[W]] = {
    val promise = Promise[Option[W]]()
    val reader  = new FileReader
    reader.onload = (_: UIEvent) => {
      val s = reader.result.asInstanceOf[R]
      promise.success(Option(conv(s)))
    }
    reader.onerror = (_: Event) => {
      promise.success(None)
    }
    doRead(reader)
    F.liftIO(IO.fromFuture(IO(promise.future)))
  }
} 
Example 16
Source File: I18N.scala    From scala-js-chrome   with MIT License 5 votes vote down vote up
package chrome.i18n

import scala.concurrent.{Future, Promise}
import scala.scalajs.js
import chrome.utils.ErrorHandling._

import js.JSConverters._
import scala.scalajs.js.|

object I18N {

  def getAcceptLanguages: Future[js.Array[String]] = {
    val promise = Promise[js.Array[String]]()
    bindings.I18N.getAcceptLanguages((languages: js.Array[String]) => {
      promise.complete(lastErrorOrValue(languages))
    })
    promise.future
  }

  def getMessage(messageName: String, substitutions: String*): js.UndefOr[String] = {
    if(substitutions.isEmpty) {
      bindings.I18N.getMessage(messageName)
    } else {
      val jsArraySubstitutions = substitutions.toJSArray.asInstanceOf[String | js.Array[String]]
      bindings.I18N.getMessage(messageName, Some(jsArraySubstitutions).orUndefined)
    }
  }

  def getUILanguage: String = bindings.I18N.getUILanguage()

} 
Example 17
Source File: ContextMenus.scala    From scala-js-chrome   with MIT License 5 votes vote down vote up
package chrome.contextMenus.bindings

import chrome.events.bindings.Event
import chrome.tabs.bindings.Tab

import scala.scalajs.js
import scala.scalajs.js.annotation.JSGlobal
import scala.scalajs.js.|

object MenuContexts {
  val ALL = "all"
  val PAGE = "page"
  val FRAME = "frame"
  val SELECTION = "selection"
  val LINKE = "link"
  val EDITABLE = "editable"
  val IMAGE = "image"
  val VIDEO = "video"
  val AUDIO = "audio"
  val LAUNCHER = "launcher"
  val BROWSER_ACTION = "browser_action"
  val PAGE_ACTION = "page_action"
}

object MenuType {
  val NORMAL = "normal"
  val CHECKBOX = "checkbox"
  val RADIO = "radio"
  val SEPARATOR = "separator"
}

@js.native
@JSGlobal("chrome.contextMenus")
object ContextMenus extends js.Object {

  def create(createProperties: CreateProperties): String | Int = js.native

  def update(id: String | Int, properties: UpdateProperties): Unit = js.native

  def remove(menuItemId: String | Int,
             callback: js.Function0[Unit]): String | Int = js.native

  def removeAll(callback: js.Function0[Unit]): Unit = js.native

  val onClicked: Event[js.Function2[MenuInfo, Tab, _]] = js.native

}

class UpdateProperties(
    val `type`: String = MenuType.NORMAL,
    val title: String,
    val checked: js.UndefOr[Boolean] = js.undefined,
    val contexts: js.UndefOr[js.Array[String]] = js.undefined,
    val onclick: js.UndefOr[js.Function2[MenuInfo, Tab, Unit]],
    val parentId: js.UndefOr[String | Int] = js.undefined,
    val documentUrlPatterns: js.UndefOr[js.Array[String]] = js.undefined,
    val targetUrlPatterns: js.UndefOr[js.Array[String]] = js.undefined,
    val enabled: Boolean = true
) extends js.Object

object CreateProperties {

  def apply(id: String,
            title: String,
            contexts: js.Array[String] = js.Array(MenuContexts.ALL))
    : CreateProperties =
    new CreateProperties(id = id, title = title, contexts = contexts)
}

class CreateProperties(
    val `type`: String = MenuType.NORMAL,
    val id: String | Int,
    val title: String,
    val checked: js.UndefOr[Boolean] = js.undefined,
    val contexts: js.UndefOr[js.Array[String]] = js.undefined,
    val onclick: js.UndefOr[js.Function2[MenuInfo, Tab, Unit]] = js.undefined,
    val parentId: js.UndefOr[String | Int] = js.undefined,
    val documentUrlPatterns: js.UndefOr[js.Array[String]] = js.undefined,
    val targetUrlPatterns: js.UndefOr[js.Array[String]] = js.undefined,
    val enabled: Boolean = true
) extends js.Object

@js.native
trait MenuInfo extends js.Object {
  val menuItemId: String | Int = js.native
  val parentMenuItemId: js.UndefOr[String | Int]
  val mediaType: js.UndefOr[String]
  val linkUrl: js.UndefOr[String]
  val srcUrl: js.UndefOr[String]
  val pageUrl: js.UndefOr[String]
  val frameUrl: js.UndefOr[String]
  val selectionText: js.UndefOr[String]
  val editable: Boolean
  val wasChecked: js.UndefOr[Boolean]
  val checked: js.UndefOr[Boolean]
} 
Example 18
Source File: ContextMenus.scala    From scala-js-chrome   with MIT License 5 votes vote down vote up
package chrome.contextMenus

import chrome.ChromeAPI
import chrome.contextMenus.bindings.{CreateProperties, MenuInfo, UpdateProperties}
import chrome.events.EventSource
import chrome.events.EventSourceImplicits._
import chrome.permissions.Permission.API
import chrome.tabs.bindings.Tab

import scala.concurrent.{Future, Promise}
import scala.scalajs.concurrent.JSExecutionContext.Implicits.queue
import scala.scalajs.js
import scala.scalajs.js.|

object ContextMenus extends ChromeAPI {

  def onClicked: EventSource[(MenuInfo, Tab)] = bindings.ContextMenus.onClicked

  val requiredPermissions: Set[API] = Set(API.ContextMenus)

  def create(createProperties: CreateProperties): String | Int =
    bindings.ContextMenus.create(createProperties)

  def create(id: String, title: String, contexts: List[String]): String | Int =
    create(
        bindings
          .CreateProperties(id, title, contexts = js.Array(contexts: _*)))

  def update(id: String | Int, properties: UpdateProperties): Unit =
    bindings.ContextMenus.update(id, properties)

  def remove(menuItemId: String | Int): Future[String | Int] = {
    val promise = Promise[Unit]
    val result = bindings.ContextMenus
      .remove(menuItemId, js.Any.fromFunction0[Unit](() => {
        promise.success(Unit)
      }))
    promise.future.map(_ => result)
  }

  def removeAll(): Future[Unit] = {
    val promise = Promise[Unit]
    bindings.ContextMenus.removeAll(js.Any.fromFunction0[Unit](() => {
      promise.success(Unit)
    }))
    promise.future
  }

} 
Example 19
Source File: BadgeBackgroundColorDetails.scala    From scala-js-chrome   with MIT License 5 votes vote down vote up
package chrome.browserAction.bindings

import scala.scalajs.js
import scala.scalajs.js.|
import scala.scalajs.js.|.Evidence

@js.native
trait BadgeBackgroundColorDetails extends TabIdDetails {
  val color: String | js.Array[Int] = js.native
}

object BadgeBackgroundColorDetails {
  // implicitly summon evidence that our union type subclasses js.Any
  implicit val colorEvidence: Evidence[String | js.Array[Int], js.Any] = implicitly

  def apply(color: String | js.Array[Int], tabId: js.UndefOr[Int] = js.undefined): BadgeBackgroundColorDetails = {
    js.Dynamic
      .literal(
        color = color.merge[js.Any],
        tabId = tabId
      )
      .asInstanceOf[BadgeBackgroundColorDetails]
  }
} 
Example 20
Source File: IconDetails.scala    From scala-js-chrome   with MIT License 5 votes vote down vote up
package chrome.browserAction.bindings

import org.scalajs.dom.ImageData

import scala.scalajs.js
import scala.scalajs.js.|
import scala.scalajs.js.|.Evidence

@js.native
trait IconDetails extends TabIdDetails {
  val imageData: js.UndefOr[ImageData | js.Dictionary[ImageData]] = js.native

  val path: js.UndefOr[String | js.Dictionary[String]] = js.native
}

object IconDetails {
  // implicitly summon evidence that our union types subclass js.Any
  implicit val imageEvidence: Evidence[ImageData | js.Dictionary[ImageData], js.Any] = implicitly
  implicit val pathEvidence: Evidence[String | js.Dictionary[String], js.Any] = implicitly

  def apply(imageData: js.UndefOr[ImageData | js.Dictionary[ImageData]] = js.undefined,
            path: js.UndefOr[String | js.Dictionary[String]] = js.undefined,
            tabId: js.UndefOr[Int] = js.undefined): IconDetails = {
    // explicitly merge our union types so that dynamic is happy
    val anyImageData: js.UndefOr[js.Any] = imageData.map(_.merge)
    val anyPath: js.UndefOr[js.Any] = path.map(_.merge)

    if (anyImageData.isDefined) {
      js.Dynamic
        .literal(
          imageData = anyImageData,
          tabId = tabId
        )
        .asInstanceOf[IconDetails]
    }
    else {
      js.Dynamic
        .literal(
          path = anyPath,
          tabId = tabId
        )
        .asInstanceOf[IconDetails]
    }
  }
} 
Example 21
Source File: BrowserAction.scala    From scala-js-chrome   with MIT License 5 votes vote down vote up
package chrome.browserAction

import chrome.browserAction.bindings._
import chrome.events.bindings.Event
import chrome.tabs.bindings.Tab
import org.scalajs.dom.ImageData

import scala.concurrent.{Future, Promise}
import scala.scalajs.js
import scala.scalajs.js.|

object BrowserAction {
  val onClicked: Event[js.Function1[Tab, _]] = bindings.BrowserAction.onClicked

  def setTitle(title: String, tabId: js.UndefOr[Int] = js.undefined): Unit = {
    bindings.BrowserAction.setTitle(TitleDetails(title, tabId))
  }

  def getTitle(tabId: js.UndefOr[Int] = js.undefined): Future[String] = {
    val promise = Promise[String]()
    bindings.BrowserAction.getTitle(TabIdDetails(tabId), (result: String) => {
      promise.success(result)
    })
    promise.future
  }

  def setIconImageData(imageData: js.UndefOr[ImageData | js.Dictionary[ImageData]],
                       tabId: js.UndefOr[Int] = js.undefined): Future[Unit] = {
    setIcon(imageData, js.undefined, tabId)
  }

  def setIconPath(pathData: js.UndefOr[String | js.Dictionary[String]],
                  tabId: js.UndefOr[Int] = js.undefined): Future[Unit] = {
    setIcon(js.undefined, pathData, tabId)
  }

  def setIcon(imageData: js.UndefOr[ImageData | js.Dictionary[ImageData]],
              pathData: js.UndefOr[String | js.Dictionary[String]],
              tabId: js.UndefOr[Int]): Future[Unit] = {
    val promise = Promise[Unit]()
    bindings.BrowserAction.setIcon(IconDetails(imageData, pathData, tabId), () => {
      promise.success(())
    })

    promise.future
  }

  def setPopup(popup: String, tabId: js.UndefOr[Int] = js.undefined): Unit = {
    bindings.BrowserAction.setPopup(PopupDetails(popup, tabId))
  }

  def getPopup(tabId: js.UndefOr[Int] = js.undefined): Future[String] = {
    val promise = Promise[String]()
    bindings.BrowserAction.getPopup(TabIdDetails(tabId), (result: String) => {
      promise.success(result)
    })
    promise.future
  }

  def setBadgeText(text: String, tabId: js.UndefOr[Int] = js.undefined): Unit = {
    bindings.BrowserAction.setBadgeText(BadgeTextDetails(text, tabId))
  }

  def getBadgeText(tabId: js.UndefOr[Int] = js.undefined): Future[String] = {
    val promise = Promise[String]()
    bindings.BrowserAction.getBadgeText(TabIdDetails(tabId), (result: String) => {
      promise.success(result)
    })
    promise.future
  }

  def setBadgeBackgroundColor(color: String | js.Array[Int]): Unit = {
    bindings.BrowserAction.setBadgeBackgroundColor(BadgeBackgroundColorDetails(color))
  }

  def getBadgeBackgroundColor(tabId: js.UndefOr[Int] = js.undefined): Future[js.Array[Int]] = {
    val promise = Promise[js.Array[Int]]()
    bindings.BrowserAction.getBadgeBackgroundColor(TabIdDetails(tabId), (result: js.Array[Int]) => {
      promise.success(result)
    })
    promise.future
  }

  def enable(tabId: js.UndefOr[Int]): Unit = {
    bindings.BrowserAction.enable(tabId)
  }

  def disable(tabId: js.UndefOr[Int]): Unit = {
    bindings.BrowserAction.disable(tabId)
  }
} 
Example 22
Source File: TooltipUtils.scala    From udash-core   with Apache License 2.0 5 votes vote down vote up
package io.udash.bootstrap
package tooltip

import com.avsystem.commons.misc.{AbstractValueEnum, AbstractValueEnumCompanion, EnumCtx}
import io.udash.wrappers.jquery._
import org.scalajs.dom

import scala.collection.mutable
import scala.concurrent.duration.{Duration, DurationInt}
import scala.scalajs.js
import scala.scalajs.js.|

trait Tooltip extends Listenable {

  override final type EventType = TooltipEvent

  
  def apply(
    animation: Boolean = true,
    boundary: String | dom.Node = "scrollParent",
    container: Option[String | dom.Node] = None,
    content: js.Function1[dom.Node, String] | dom.Node = io.udash.emptyStringNode(),
    delay: Delay | Long = Delay(0 millis, 0 millis),
    html: Boolean = false,
    offset: Int | String = "0",
    placement: Placement = defaultPlacement,
    template: Option[String] = None,
    title: String | js.Function1[dom.Node, String] | dom.Node = "",
    trigger: Seq[Trigger] = defaultTrigger
  )(el: dom.Node): TooltipType =
    initTooltip(
      js.Dictionary(
        "animation" -> animation,
        "boundary" -> boundary,
        "container" -> container.getOrElse(false),
        "content" -> content,
        "delay" -> delay,
        "html" -> html,
        "offset" -> offset,
        "placement" -> placement.jsValue,
        "template" -> template.getOrElse(defaultTemplate),
        "title" -> title,
        "trigger" -> trigger.map(_.jsValue).mkString(" ")
      )
    )(el)

  protected def initTooltip(options: js.Dictionary[Any])(el: dom.Node): TooltipType
  protected val defaultPlacement: Placement
  protected val defaultTemplate: String
  protected val defaultTrigger: Seq[Trigger]
} 
Example 23
Source File: MutableNestedArray.scala    From outwatch   with Apache License 2.0 5 votes vote down vote up
package outwatch.helpers

import scala.scalajs.js
import scala.scalajs.js.|

private[outwatch] class MutableNestedArray[T] {
  private val array = new js.Array[T | MutableNestedArray[T]]

  // not safe if T = MutableNestedArray.
  def foreach(f: T => Unit): Unit = array.foreach(a => (a: Any) match {
    case nested: MutableNestedArray[T] => nested.foreach(f)
    case t: T@unchecked => f(t)
  })

  @inline def push(value: T | MutableNestedArray[T]): Unit = { array.push(value); () }
  @inline def clear(): Unit = array.clear()
  @inline def isEmpty(): Boolean = array.isEmpty
} 
Example 24
Source File: TypescriptCompiler.scala    From Demos   with MIT License 5 votes vote down vote up
package demo

import typings.node.global.console
import typings.node.processMod.{^ => process}
import typings.typescript.{mod => ts}

import scala.scalajs.js
import scala.scalajs.js.|

object TypescriptCompiler {
  def compile(fileNames: js.Array[String], options: ts.CompilerOptions): Unit = {
    val program: ts.Program = ts.createProgram(fileNames, options)
    val emitResult = program.emit()

    val allDiagnostics = ts
      .getPreEmitDiagnostics(program)
      .concat(emitResult.diagnostics)

    allDiagnostics.foreach(diagnostic => {
      val baseMessage = ts.flattenDiagnosticMessageText(Knowledge.force(diagnostic.messageText), "\n")

      val message = diagnostic.file.fold(baseMessage) { file =>
        val pos = file.getLineAndCharacterOfPosition(diagnostic.start.get)
        s"${diagnostic.file.get.fileName} (${pos.line + 1},${pos.character + 1}): $baseMessage"
      }

      console.log(message)
    })

    val exitCode = if (emitResult.emitSkipped) 1 else 0
    console.log(s"Process exiting with code '$exitCode'.")
    process.exit(exitCode)
  }

  def main(args: Array[String]): Unit = {
    val files: js.Array[String] =
      process.argv.drop(2) match {
        case empty if empty.length == 0 =>
          js.Array(
            "typescript/src/main/resources/good.ts",
            "typescript/src/main/resources/bad.ts"
          )
        case nonEmpty => nonEmpty
      }

    compile(
      files,
      ts.CompilerOptions().setNoEmitOnError(true).setNoImplicitAny(true).setOutDir("typescript/target/temp")
    )
  }
}

object Knowledge {
  def force(a: String | ts.DiagnosticMessageChain): ts.DiagnosticMessageChain =
    a.asInstanceOf[ts.DiagnosticMessageChain]
} 
Example 25
Source File: D3Demo.scala    From Demos   with MIT License 5 votes vote down vote up
package demo

import typings.d3.{mod => d3Mod}
import typings.d3Geo.mod.{GeoContext, GeoProjection_}
import typings.geojson.geojsonStrings
import typings.geojson.mod.{LineString, Position}
import typings.std.global.{console, document, window}
import typings.std.{stdStrings, CanvasRenderingContext2D, FrameRequestCallback, HTMLCanvasElement}

import scala.scalajs.js
import scala.scalajs.js.|

object D3Demo {
  def main(argv: scala.Array[String]): Unit = {
    val canvas: HTMLCanvasElement =
      document
        .getElementsByTagName_canvas(stdStrings.canvas)(0)
        .getOrElse(sys.error("Cannot find canvas element"))

    Knowledge.asOption(canvas.getContext_2d(stdStrings.`2d`)) match {
      case Some(ctx) => run(ctx)
      case None      => console.warn("Cannot get 2d context for", canvas)
    }
  }

  def run(context: CanvasRenderingContext2D): Double = {

    context.lineWidth   = 0.4
    context.strokeStyle = "rgba(255, 255, 255, 0.6)"

    val width  = window.innerWidth
    val height = window.innerHeight
    val size: Double = width min height

    d3Mod
      .select("#content")
      .attr("width", s"${width}px")
      .attr("height", s"${height}px")

    val projection: GeoProjection_ =
      d3Mod
        .geoOrthographic()
        .scale(0.45 * size)
        .translate(js.Tuple2(0.5 * width, 0.5 * height))

    val geoGenerator =
      d3Mod.geoPath(projection, Knowledge.isGeoContext(context))

    val geometry = LineString(
      coordinates = js.Array[Position](),
      `type`      = geojsonStrings.LineString
    )

    def rndLon = -180 + Math.random() * 360
    def rndLat = -90 + Math.random() * 180

    def addPoint(): Unit =
      geometry.coordinates.push(js.Array(rndLon, rndLat))

    def update: FrameRequestCallback =
      (time: Double) => {
        if (geometry.coordinates.length < 6000) addPoint()

        projection.rotate(js.Tuple2(time / 100, 1.0))

        context.clearRect(0, 0, width, height)
        context.beginPath()

        geoGenerator(geometry, null)
        context.stroke()

        window.requestAnimationFrame(update)
      }

    window.requestAnimationFrame(update)
  }
}

object Knowledge {
  def isGeoContext(ctx: CanvasRenderingContext2D): GeoContext =
    ctx.asInstanceOf[GeoContext]
  def asOption[T](t: T | Null): Option[T] =
    Option(t.asInstanceOf[T])
} 
Example 26
Source File: JQueryDemo.scala    From Demos   with MIT License 5 votes vote down vote up
package demo

import org.scalajs.dom.html.{Button, Label}
import org.scalajs.dom.document
import org.scalajs.dom.raw.Element
import typings.jquery.{JQueryEventObject, JQuery_, mod => $}
import typings.jqueryui.jqueryuiRequire

import scala.scalajs.js
import scala.scalajs.js.annotation.JSImport
import scala.scalajs.js.|

object JQueryDemo {
  @JSImport("jqueryui/jquery-ui.css", JSImport.Namespace)
  @js.native
  object JqueryUiCss extends js.Object

   JQueryEventObject, scala.Unit] = eo => {
      counter += 1
      $[Label]("#label").text(s"Value is $counter")
    }

    $[Button]("#button")
      .text("bumpit")
      .on("click", renderLabel)

    isJQueryUi($("#accordion")).accordion()
  }
} 
Example 27
Source File: LodashDemo.scala    From Demos   with MIT License 5 votes vote down vote up
package demo

import org.scalablytyped.runtime.NumberDictionary
import typings.lodash.mod.{ArrayIterator, MemoListIterator, ^ => L}
import typings.lodash.{fpMod => Fp}
import typings.node.global.console
import typings.std.ArrayLike

import scala.scalajs.js
import scala.scalajs.js.|

object LodashDemo {

  class Person(val name: String, val age: Int) extends js.Object

  val Fiona   = new Person("Fiona First", 1)
  val Sam     = new Person("Sam Second", 101)
  val Persons = js.Array(Fiona, Sam)

  def main(args: Array[String]): Unit = {

    val summarizeNames
        : MemoListIterator[Person, js.UndefOr[String], js.Array[Person] | typings.lodash.mod.List[Person]] =
      (prevU, curr, idx, all) =>
        prevU.fold(curr.name) { prev =>
          prev + " and " + curr.name
        }

    val value2 = L.reduce[Person, js.UndefOr[String]](Persons, summarizeNames, js.undefined)
    console.log("Summarized names of two persons", value2)

    val value3 = L.reduce[Person, js.UndefOr[String]](js.Array[Person](), summarizeNames, js.undefined)
    console.log("Summarized names of no persons", value3)

    val toAge: ArrayIterator[Person, Int] =
      (curr, _, _) => curr.age

    console.log("Ages for persons", L.map(Persons.asInstanceOf[NumberDictionary[Double]], toAge))

    console.log("fields for Fiona", L.entriesIn(Fiona))

    console.log("Dropped first", Fp.^.drop(1, Knowledge.isArrayLike(Persons)))
  }
}

object Knowledge {
  def isArrayLike[T](ts: js.Array[T]): ArrayLike[T] =
    ts.asInstanceOf[ArrayLike[T]]
}